package com.guigu.eduservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.entity.EquipmentReservation;
import com.guigu.eduservice.service.*;
import com.guigu.eduservice.vo.OrderShouVo;
import org.springframework.beans.factory.annotation.Autowired;

import com.guigu.common.utils.R;
import com.guigu.eduservice.entity.Order;
import com.guigu.eduservice.service.OrderService;
import com.guigu.eduservice.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageInfo;
import com.guigu.eduservice.dto.OrderListDTO;
import com.guigu.eduservice.dto.OrderQueryDTO;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import javax.xml.ws.Action;

/**
 * <p>
 * 订单表（存储买卖双方的交易订单信息） 前端控制器
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/eduservice/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private EquipmentReservationService equipmentReservationService;



    //传入订单ID，修改状态，返回`是否成功
    @GetMapping("/updateOrderStatus/{id}/{status}")
    public R updateOrderStatus(@PathVariable("id") Long id,@PathVariable("status") int status){
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        if (id==null){
            return R.error().message("订单ID不能为空");
        }
        wrapper.set("order_status", status)
                .set("receipt_time", LocalDateTime.now())
                .eq("order_id", id);
        boolean update = orderService.update(wrapper);

        return update ? R.ok() : R.error();
    }
    @GetMapping("/updateOrderStatus2/{id}/{status}")
    public R updateOrderStatus2(@PathVariable("id") Long id,@PathVariable("status") int status){
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        if (id==null){
            return R.error().message("订单ID不能为空");
        }
        wrapper.set("order_status", status)
                .set("evaluation_time", LocalDateTime.now())
                .eq("order_id", id);
        boolean update = orderService.update(wrapper);

        return update ? R.ok() : R.error();
    }
    @GetMapping("/updateOrderStatus3/{id}/{status}")
    public R updateOrderStatus3(@PathVariable("id") Long id,@PathVariable("status") int status){
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        if (id==null){
            return R.error().message("订单ID不能为空");
        }
        wrapper.set("order_status", status)
                .eq("order_id", id);
        boolean update = orderService.update(wrapper);
        LambdaQueryWrapper<Order> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Order::getOrderId, id);
        Order order = orderService.getOne(wrapper2);
        if (order==null){
            return R.error().message("订单不存在");
        }
        if (update){
            LambdaQueryWrapper<Equipment> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(Equipment::getEquipmentId, order.getEquipmentId());
            Equipment equipment = equipmentService.getOne(wrapper1);
            if (equipment==null){
                return R.error().message("设备不存在");
            }
            equipment.setStatus(1);
            equipmentService.update(equipment,wrapper1);
            LambdaQueryWrapper<EquipmentReservation> equipmentReservationLambdaQueryWrapper = new LambdaQueryWrapper<>();
            equipmentReservationLambdaQueryWrapper.eq(EquipmentReservation::getEquipmentId, order.getEquipmentId());
            EquipmentReservation one = equipmentReservationService.getOne(equipmentReservationLambdaQueryWrapper);
            if (one!= null){
               one.setReservationStatus(3);
               one.setCancelTime(new Date());
               one.setCancelReason("用户放弃购买");
               equipmentReservationService.update(one,equipmentReservationLambdaQueryWrapper);
            }

        }

        return update ? R.ok() : R.error();
    }

    //传入用户ID，状态，返回订单集合
    @PostMapping("/selectOrderByUId")
    public R selectOrderByUId(@RequestBody OrderVo vo){
        List<Order> list = orderService.selectOrderByUId(vo);
        return R.ok().data("list",list);
    }
    @GetMapping("getOrderList")
    public R getOrderList(OrderQueryDTO query) {
        return R.ok().data("list", orderService.getOrderList(query));
    }

   @DeleteMapping("/deleteOrder/{orderId}")
    public R deleteOrder(@PathVariable Long orderId) {
        return orderService.removeById(orderId) ? R.ok() : R.error();
    }

    @PutMapping("updateOrder")
    public boolean updateOrder(@RequestBody OrderQueryDTO dto) {
        return orderService.updateOder(dto);
    }

    /**
     * 前台-根据买家的id和已完成的状态去查询该买家购买的全部订单设备信息
     *
     * @param
     * @return
     */
    @GetMapping("/selectOrderBybuyerIdAndorderStatus/{id}/{pageNum}/{pageSize}")
    public R selectOrderBybuyerIdAndorderStatus(@PathVariable("id") Long id, @PathVariable("pageNum") Integer pageNum,
                                                @PathVariable("pageSize") Integer pageSize) {

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.eq("buyer_id", id);


        List<Order> list = orderService.list(orderQueryWrapper);

        for (Order order : list) {
            //远程调用-查询设备的信息
            Equipment equipment = equipmentService.queryEquipmentAndImageAndType2(order.getEquipmentId());
            order.setEquipment(equipment);
        }

        int total = list.size();
        int startIndex = (pageNum - 1) * pageSize;

        // 边界检查：确保 startIndex 不超过总数据量
        if (startIndex >= total) {
            // 如果起始索引超出范围，返回空列表
            return R.ok()
                    .data("list", new ArrayList<>())
                    .data("total", total);
        }

        int endIndex = Math.min(startIndex + pageSize, total);
        List<Order> orders = list.subList(startIndex, endIndex);

        return R.ok()
                .data("orders", orders)
                .data("total", total);
    }

    /**
     * 后台-获取订单的统计信息
     *
     * @return
     */
    @GetMapping("monthly-transactions")
    public R monthlyTransactions() {
        return R.ok().data("list", orderService.getDashboardStats());
    }

    @GetMapping("/stats")
    public R getDashboardStats() {
        Map<String, Object> data = new HashMap<>();

        // 获取今日新增设备数
        int todayDeviceCount = equipmentService.getTodayDeviceCount();
        data.put("todayDeviceCount", todayDeviceCount);

        // 获取今日付款订单数
        int todayPaidOrderCount = orderService.getTodayPaidOrderCount();
        data.put("todayPaidOrderCount", todayPaidOrderCount);

        // 获取今日付款金额
        BigDecimal todayPaidAmount = orderService.getTodayPaidAmount();
        data.put("todayPaidAmount", todayPaidAmount != null ? todayPaidAmount : BigDecimal.ZERO);
        return R.ok().data(data);
    }

    @PutMapping("/addOrderShouHuo")
    public R addOrderShouHuo(@RequestBody OrderShouVo vo){//确认发货
        if (vo==null){
            return R.error().message("参数不能为空");
        }
        if (vo.getOId()==null){
            return R.error().message("订单ID不能为空");
        }
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderId,vo.getOId());
        Order one = orderService.getOne(wrapper);
        if (one==null){
            return R.error().message("订单不存在");
        }
        one.setOrderStatus(vo.getOrderStatusVo());
        if (vo.getLogisticsCompanyVo()!=null){
            one.setLogisticsCompany(vo.getLogisticsCompanyVo());
        }
        if (vo.getLogisticsNoVo()!=null){
            one.setLogisticsNo(vo.getLogisticsNoVo());
        }
        boolean update = orderService.update(one, wrapper);
        return update ? R.ok() : R.error();
    }

}
